import java.io.DataInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;
import edu.stanford.nlp.tagger.maxent.*;

public class QA {
	
	public static MaxentTagger tagger;
	static ArrayList<Integer> nums;
	static String[] questions;
	
	public static void main (String args[]) {
		try {
			tagger = new MaxentTagger("Stanford/models/left3words-wsj-0-18.tagger");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		questions = parse("questions.txt");
		for (int i = 0; i < questions.length; i++) {
			//System.out.println(questions[i].toString());
			//Who w = parseQuestion(questions[i]);
		}
		for (int i = 0; i < questions.length; i++) {
			parseQuestion(i);
		}
	}
	
	//Parse a file and find all "who" questions. Return a Who array.
	public static String[] parse(String filename) {
		try {
			FileInputStream fstream = new FileInputStream(filename);
			DataInputStream in = new DataInputStream(fstream);

			byte[] b = new byte[in.available()];
			in.read(b);
			
			String text = new String(b);
			
			ArrayList<String> list = new ArrayList<String>();
			nums = new ArrayList<Integer>();
			
			int num = 0;
			StringTokenizer st = new StringTokenizer(text,"\n");
			while (st.hasMoreTokens()) {
				String token = st.nextToken();
				if (token.contains("Number: ")) {
					String number = token.substring(token.length() - 4, token.length() - 1);
					num = Integer.parseInt(number);
				}
				if (token.contains("Who")) {
					list.add(token);
					nums.add(num);
				}
			}
			
			String[] w = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				w[i] = list.get(i).substring(0, list.get(i).length() - 1);
			}
			
			return w;
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Who parseQuestion(int n) {
		return parseQuestion(questions[n], nums.get(n));
	}
	
	public static Who parseQuestion(String question, int num) {
		if (!(question.contains("Who is") || question.contains("Who was"))) return new WhoDid(question, num);
		String tagged = tagger.tagString(question);
		
		
		if (!tagged.contains("NN") && !tagged.contains("NNP")) System.out.println("What"); 
		if (!tagged.contains("NN ") && !tagged.contains("the")) return new WhoDescription(question, num);
		
		return new WhoDid(question, num);
	}
}
